#!/usr/bin/env bash
### BEGIN INIT INFO
# Provides:          cow
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: starts cow
# Description:       starts cow
### END INIT INFO
###############################################
# shadowsocks cow service bash
# @see https://github.com/cyfdecyf/cow
# @author Janpoem<janpoem@163.com>
###############################################

NAME=cow
DESC="shadowsocks-cow"
CONFFILE=/root/.cow/rc
LOGFILE=/var/log/cow.log
PIDFILE=/var/run/cow.pid
DAEMON=/usr/local/bin/cow
DAEMON_ARGS="-rc=${CONFFILE}"
CMD="${DAEMON}"

. /lib/lsb/init-functions

check_proc() {
	[ ! -f "${PIDFILE}" ] && return 0
	if ps -p $(cat $PIDFILE) > /dev/null 2>&1
	then
		return 1
	else
		return 0
	fi
}

show_proc() {
	if [ ! -f "${PIDFILE}" ]; then
		echo "Process file ${PIDFILE} does not exist!"
		return 0
	fi

	/bin/ps -p "$(cat ${PIDFILE})"
	return 0
}

start_proc() {
	check_proc
	case "$?" in
		0)
			start-stop-daemon \
				--start \
				--quiet --background \
				--pidfile ${PIDFILE} --make-pidfile \
				--exec ${DAEMON} -- ${DAEMON_ARGS} 2>/dev/null \
				|| return 2
			;;
		1)
			# 进程已经存在，没啥可做
			return 1
			;;
	esac
}

stop_proc()
{
	start-stop-daemon --stop --quiet --oknodo --pidfile ${PIDFILE}
	RETVAL="$?"
	[ "${RETVAL}" = 2 ] && return 2
	rm -f ${PIDFILE}
	return "${RETVAL}"
}

case "$1" in
    start)
        log_daemon_msg "Starting ${DESC}" "${NAME}"
		start_proc
		case "$?" in
            0)
				log_end_msg 0  # 启动成功 		log_end_msg 0 是OK
				;;
            1)
				log_end_msg 1  # 进程已经存在 	log_end_msg 1 是fail
				echo "The process ${DAEMON} is existing!"
				;;
			2)
				log_end_msg 1  # 启动失败		log_end_msg 1 是fail
				echo "Unknown error!"
				;;
        esac
        ;;
    stop)
        log_daemon_msg "Stopping ${DESC}" "${NAME}"
        stop_proc
        case "$?" in
			0|1) log_end_msg 0 ;;
			2) log_end_msg 1 ;;
        esac
        ;;
    status)
        status_of_proc "${DAEMON}" "${NAME}" && exit 0 || exit $?
        ;;
    restart)
        log_daemon_msg "Restarting ${DESC}" "${NAME}"
        stop_proc
        case "$?" in
        	0|1)
				start_proc
				case "$?" in
					0)
						log_end_msg 0  # 启动成功 		log_end_msg 0 是OK
						;;
					1)
						log_end_msg 1  # 进程已经存在 	log_end_msg 1 是fail
						echo "The process ${DAEMON} is existing!"
						;;
					2)
						log_end_msg 1  # 启动失败		log_end_msg 1 是fail
						echo "Unknown error!"
						;;
				esac
                ;;
        	*)
                # Failed to stop
                log_end_msg 1
                ;;
        esac
        ;;
	proc)
		show_proc
		;;
    *)
        echo "Usage: /etc/init.d/mcrouter {start|stop|status|restart|proc}"
        exit 1
        ;;
esac
